using DotNetCore.CAP;
using NP.BPMReportPlatform.Common;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.EmailHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Business.Cadre;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.RecurringJobs;
using NP.BPMReportPlatform.RecurringJobs.Dto;
using SqlSugar;
using System;
using System.Linq;
using System.Threading.Tasks;
using static NP.BPMReportPlatform.Cadre.Enum.CadreEnum;

namespace NP.BPMReportPlatform.Cadre
{
    /// <summary>
    /// 干部转身同步接口
    /// </summary>
    public class CadreSyncJob : BpmReportPlatformRecurringJob, ICadreSyncJob
    {
        private readonly SqlSugarClient _db, _dbPlatform;
        private readonly IEmailAPPService _emailAPPService;
        private ICapPublisher _capBus;
        private readonly ICommonService _commonService;

        public CadreSyncJob(ISqlSugarAppService sqlSugarAppService, IEmailAPPService emailAPPService, ICapPublisher capPublisher, ICommonService commonService)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _emailAPPService = emailAPPService;
            _capBus = capPublisher;
            _commonService = commonService;
        }

        /// <summary>
        /// 定时任务入口
        /// </summary>
        /// <returns></returns>
        public Task CadreJob()
        {
            SendCadreEmail(CadreEmailEnum.导师辅导记录提交提醒, string.Empty);
            SendCadreEmail(CadreEmailEnum.转身计划总结流程提醒, string.Empty);
            SendCadreEmail(CadreEmailEnum.上岗前沟通记录提醒, string.Empty);
            return Task.CompletedTask;
        }

        /// <summary>
        /// 推送邮件
        /// </summary>
        public void SendCadreEmail(CadreEmailEnum type, string id)
        {
            string topic = string.Empty;
            string templateName = string.Empty;
            string to = string.Empty;
            string url = ConfigManager.HRBPMReportUrl + "/cadre/cadre-list";
            // 转身状态变更为【转身计划制定】，1.邮件发送给HRBP，提醒发起转身计划制定流程(带链接，可直达表单发起页面)
            // 定时任务：2.助力开始时间1个月后，如果干部没有提交导师辅导记录，则【邮件】提醒，后续，每隔1个月，提醒1次，辅导记录提交3次后，不再提醒
            // BPM流程提交后 3.干部提交转身计划总结后，【邮件】通知给HRBP，HRBP登录系统进行转身述职
            // 定时任务：4.助力开始日期150天后，发送邮件通知HRBP需要启动转身计划总结流程(带链接，可直达表单发起页面)
            switch (type)
            {
                case CadreEmailEnum.上岗前沟通记录提醒:
                    templateName = "CadreStartNotice.cshtml";
                    var time = DateTime.Now.AddDays(-10);
                    var start = new DateTime(time.Year, time.Month, time.Day);
                    var end = start.AddDays(1).AddMinutes(-1);
                    var caderStarts = _db.Queryable<CadreEntity>().Where(t => t.Status == CadreStatusEnum.上岗前沟通.GetHashCode() && t.StartDate <= start).ToList();
                    if (caderStarts != null && caderStarts.Count() > 0)
                    {
                        foreach (var item in caderStarts)
                        {
                            var touser = _dbPlatform.Queryable<Users>().Where(t => t.WorkNumber == item.WorkNumber).First();
                            to = touser?.Email;
                            topic = $"[系统邮件，请勿回复]{item.UserName}({item.WorkNumber})的上岗前沟通记录录入提醒";
                            object oc = new { LeaderName = item.LeaderName, UserName = item.UserName, WorkNumber = item.WorkNumber, TeacherName = item.TeacherName, Url = url };
                            SendEmail(templateName, topic, to, oc);
                        }
                    }
                    break;
                case CadreEmailEnum.转身计划制定提醒:
                    var cadre = _db.Queryable<CadreEntity>().Where(t => t.Id == id).First();
                    topic = $"[系统邮件，请勿回复]{cadre.UserName}({cadre.WorkNumber})的转身计划制定通知";
                    templateName = "CadrePlanNotice.cshtml";
                    // TO HRBP
                    var worknumbers = _commonService.GetUserHRBPFilter(cadre.WorkNumber, Contract.Dtos.RelationshipTypeEnum.HRBP);
                    var tousers = _dbPlatform.Queryable<Users>().Where(t => worknumbers.Contains(t.WorkNumber)).ToList();
                    to = string.Join(";", tousers.Select(t => t.Email).Distinct().ToList());
                    object oa = new { HRBPName = tousers.FirstOrDefault()?.UserName, UserName = cadre.UserName, WorkNumber = cadre.WorkNumber, TeacherName = cadre.TeacherName, Url = url };

                    SendEmail(templateName, topic, to, oa);
                    break;
                case CadreEmailEnum.导师辅导记录提交提醒:
                    templateName = "CadreTeacherNotice.cshtml";
                    var listdata = _db.Queryable<CadreEntity>().Where(t => t.Status == CadreStatusEnum.转身计划执行.GetHashCode()).ToList();
                    if (listdata != null && listdata.Count() > 0)
                    {
                        // 第一次 通知 根据【助力开始日期】后30天 发送提醒  之后根据 辅导记录中的沟通日期 +30天 来提醒
                        var cadreids = listdata.Select(t => t.Id).ToList();
                        var teacherlist = _db.Queryable<CadreTeacherRecordEntity>()
                            .Where(t => SqlFunc.ContainsArray(cadreids, t.CadreId))
                            .OrderBy(t => t.CreateTime, OrderByType.Desc).ToList();
                        foreach (var item in listdata)
                        {
                            var count = teacherlist.Count(t => t.CadreId == item.Id);
                            var lasterdate = count > 0 ? teacherlist.Where(t => t.CadreId == item.Id).FirstOrDefault().TalkDate.Value : item.StartDate;
                            if (count < 3 && lasterdate < DateTime.Now.AddMonths(-1))
                            {
                                var touser = _dbPlatform.Queryable<Users>().Where(t => t.WorkNumber == item.WorkNumber).First();
                                to = touser?.Email;
                                topic = $"[系统邮件，请勿回复]{item.UserName}({item.WorkNumber})的导师辅导记录通知";
                                object oc = new { HRBPName = string.Empty, UserName = item.UserName, WorkNumber = item.WorkNumber, TeacherName = item.TeacherName, Url = url };

                                SendEmail(templateName, topic, to, oc);
                            }
                        }
                    }
                    break;
                case CadreEmailEnum.转身述职填写:
                    cadre = _db.Queryable<CadreEntity>().Where(t => t.Id == id).First();
                    topic = $"[系统邮件，请勿回复]{cadre.UserName}({cadre.WorkNumber})的转身述职通知";
                    templateName = "CadreResult.cshtml";
                    // TO HRBP
                    worknumbers = _commonService.GetUserHRBPFilter(cadre.WorkNumber, Contract.Dtos.RelationshipTypeEnum.HRBP);
                    tousers = _dbPlatform.Queryable<Users>().Where(t => worknumbers.Contains(t.WorkNumber)).ToList();
                    to = string.Join(";", tousers.Select(t => t.Email).Distinct().ToList());
                    object ob = new { HRBPName = tousers.FirstOrDefault()?.UserName, UserName = cadre.UserName, WorkNumber = cadre.WorkNumber, TeacherName = cadre.TeacherName, Url = url };
                    SendEmail(templateName, topic, to, ob);
                    break;
                case CadreEmailEnum.转身计划总结流程提醒:
                    templateName = "CadreProcessResultNotice.cshtml";
                    var datetime = DateTime.Now.AddDays(-150);
                    var cadrelistdata = _db.Queryable<CadreEntity>().Where(t => t.Status == CadreStatusEnum.转身计划执行.GetHashCode() && t.StartDate <= datetime).ToList();
                    if (cadrelistdata != null && cadrelistdata.Count() > 0)
                    {
                        foreach (var item in cadrelistdata)
                        {
                            topic = $"[系统邮件，请勿回复]{item.UserName}({item.WorkNumber})的转身计划总结流程发起通知";
                            // TO HRBP
                            worknumbers = _commonService.GetUserHRBPFilter(item.WorkNumber, Contract.Dtos.RelationshipTypeEnum.HRBP);
                            tousers = _dbPlatform.Queryable<Users>().Where(t => worknumbers.Contains(t.WorkNumber)).ToList();
                            to = string.Join(";", tousers.Select(t => t.Email).Distinct().ToList());
                            object oj = new { HRBPName = tousers.FirstOrDefault()?.UserName, UserName = item.UserName, WorkNumber = item.WorkNumber, TeacherName = item.TeacherName, Url = url };
                            SendEmail(templateName, topic, to, oj);
                        }
                    }
                    break;
                default: break;
            }
        }

        private void SendEmail(string templateName, string topic, string to, object o)
        {
            string content = string.Empty;
            if (!string.IsNullOrEmpty(templateName))
            {
                content = _emailAPPService.GenerateEmailTemplate(templateName, o);
            }

            // && ConfigManager.NeedSendEmail
            if (!string.IsNullOrEmpty(content) && !string.IsNullOrEmpty(to))
            {
                // TODO: 测试，只发给liya,上线前要去掉
                // topic = topic + ";" + to;
                // to = "liya.li@movit-tech.com;tiger.zhou@movit-tech.com";
                _capBus.PublishAsync("bpmnew.EmailAppService.SendEmailAsync",
                  new SendEmailSimpleDto()
                  {
                      To = to,
                      Subject = topic,
                      Body = content
                  });
            }
        }
    }
}
